package cn.simon.free.validator.core;

import cn.simon.free.validator.annotation.MobileValid;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * 密码强度校验
 *
 * @author simon
 * @date 2020/6/5 11:46
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Slf4j
public class MobileValidator extends Constraint implements ConstraintValidator<MobileValid, String> {
    private final String regexp = "^[1]\\d{10}$";
    private final Pattern pattern = Pattern.compile(regexp);

    @Override
    public void initialize(MobileValid constraintAnnotation) {
        super.setRequired(constraintAnnotation.required());
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (super.required) {
            return Optional.ofNullable(value).filter(v -> pattern.matcher(v).matches()).isPresent();
        }
        return true;
    }

}
